package com.example.infowall02.controller;

import com.example.infowall02.utils.AliOssUtil;
import com.example.infowall02.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

// 富文本编辑器图片上传
@Slf4j
@RestController
@RequestMapping("/richtext/image")
public class RichTextImageController {
    // 注入阿里云OSS工具类
    @Autowired
    private AliOssUtil aliOssUtil;

    // 上传图片
    @PostMapping("/upload")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            // 构建符合 wangEditor 要求的数据结构
            Map<String, String> imageData = new HashMap<>();
            imageData.put("url", filePath);
            imageData.put("alt", "文字配图"); // 图片文字说明，这里留空
            imageData.put("href", filePath); // 跳转链接，这里留空

            List<Map<String, String>> dataList = new ArrayList<>();
            dataList.add(imageData);

            response.put("errno", 0);
            response.put("data", dataList);
            log.info(response.toString());
        } catch (Exception e) {
            log.error("图片上传失败", e);
            response.put("errno", 1); // 非 0 表示有错误
            response.put("data", new ArrayList<>());
        }
        return response;
    }
}